<template>
    <el-form label-width="100px">
        <el-form-item label="SPU名称">
            <el-input placeholder="请输入SPU名称" v-model="spuParams.spuName"></el-input>
        </el-form-item>
        <el-form-item label="SPU品牌">
            <el-select style="width: 200px;" v-model="spuParams.tmId" placeholder="请选择SPU品牌">
                <el-option v-for="item in allTradeMark" :label="item.tmName" :value="item.id" :key="item.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input type="textarea" placeholder="请输入SPU描述" v-model="spuParams.description"></el-input>
        </el-form-item>
        <el-form-item label="SPU图片">
            <el-upload list-type="picture-card" v-model:file-list="imgList" action="/api/admin/product/fileUpload"
                :on-preview="handlePreview">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
                <img w-full :src="img" style="width: 100%; height: 100%; object-fit:contain">
            </el-dialog>
        </el-form-item>
        <el-form-item label="销售属性">
            <el-select v-model="saleAttrIdAndValueName"
                :placeholder="unSelectSaleAttr ? `还有${unSelectSaleAttr.length}个属性未选择` : 'ok了'" style="width: 200px;">
                <el-option v-for="item in unSelectSaleAttr" :label="item.name" :value="`${item.id}:${item.name}`"
                    :key="item.id"></el-option>
            </el-select>
            <el-button icon="Plus" type="primary" style="margin-left: 20px;" :disabled="!saleAttrIdAndValueName"
                @click="addSaleAttr">添加销售属性</el-button>
            <!-- table展示属性的地方 -->
            <el-table border style="margin: 10px 0;" :data="saleAttr">
                <el-table-column label="序号" align="center" type="index" width="80px"></el-table-column>
                <el-table-column label="销售属性" width="100px" prop="saleAttrName"></el-table-column>
                <el-table-column label="销售属性值">
                    <!-- @vue-ignore -->
                    <template #="{ row, $index }">
                        <!-- row:当前已有spu的销售属性对象 -->
                        <el-tag closable style="margin-left: 5px;line-height: 24px;"
                            v-for="(item, index) in row.spuSaleAttrValueList" :key="item.id"
                            @close="row.spuSaleAttrValueList.splice(index, 1)">
                            {{ item.saleAttrValueName }}
                        </el-tag>
                        <!-- el-input和el-button二选一-->
                        <el-input v-model="row.saleAttrValue" v-if="row.flag" placeholder="请输入属性值" size="small"
                            style="width:100px;margin-left: 10px;" @blur="toLook(row)" />
                        <el-button v-else style="margin-left: 15px;" type="success" icon="Plus" size="small"
                            @click="toEdit(row)" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100px" align="center">
                    <!-- scope.row 为当前行数据，$index 为当前行下标 -->
                    <!-- @vue-ignore -->
                    <template #="{ row, $index }">
                        <el-button icon="Delete" circle type="danger" @click="saleAttr.splice($index, 1)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="save" :disabled="!saleAttr.length">保存</el-button>
            <el-button type="warning" @click="close">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { SpuData, AllTradeMark, SpuHasImg, HasSaleAttrResponseData, SpuImg, SaleAttr, SaleAttrValue } from '@/api/product/spu/types';
import { reqAllTrademark, reqSpuImageList, reqSpuHasSaleAttr, reqAllSaleAttr, addOrUpdateSpu } from "@/api/product/spu/index"
import { TradeMark } from "@/api/product/trademark/type";
import { ElMessage } from "element-plus";
const emit = defineEmits(["changeScene", "getHasSpu"])
// 存储品牌数据
const allTradeMark = ref<TradeMark[]>([])
// 控制dialog的显示和隐藏
const dialogVisible = ref<boolean>(false)
// 存储图片数据
const imgList = ref<SpuImg[]>([])
// 存储还未收集的spu销售属性
const saleAttrIdAndValueName = ref<string>('')
// 预览图片
const img = ref<string>("")
// 已有spu销售属性
const saleAttr = ref<SaleAttr[]>([])
// 全部的销售属性
const allSaleAttr = ref<any>([])
// 存储已有的spu对象
const spuParams = ref<SpuData>({
    tmId: "",
    category3Id: "",
    description: "",
    spuName: "",
    spuImageList: [],
    spuSaleAttrList: [],
}
)
// 通知父组件切换场景值
const close = () => {
    emit("changeScene", { flag: 0, params: '' })
}
// 编辑方法
const initHasSpuData = async (spu: SpuData) => {
    // 获取全部品牌的数据
    const res: AllTradeMark = await reqAllTrademark()
    // 获取某spu下全部售卖商品的图片
    const imgsList: SpuHasImg = await reqSpuImageList((spu.id) as number)
    // 获取已有spu销售属性
    const saleAttrList = await reqSpuHasSaleAttr((spu.id) as number)
    // 获取整个项目的销售属性
    const allSaleAttrList: HasSaleAttrResponseData = await reqAllSaleAttr()
    allTradeMark.value = res.data;
    imgList.value = imgsList.data.map(item => {
        // 格式化成组件需要的格式
        return {
            name: item.imgName,
            url: item.imgUrl
        }
    });
    saleAttr.value = saleAttrList.data;
    allSaleAttr.value = allSaleAttrList.data;
    // 存储已有的spu对象，将来在模板中进行展示
    spuParams.value = spu;
}
// 添加方法
const initAddSpuData = async (c3Id: number | string) => {
    // 清空数据
    Object.assign(spuParams.value, {
        tmId: "",
        category3Id: "",
        description: "",
        spuName: "",
        spuImageList: [],
        spuSaleAttrList: [],
    })
    // 清空照片墙
    imgList.value = []
    // 清空销售属性
    saleAttr.value = []
    saleAttrIdAndValueName.value = ''
    spuParams.value.id = undefined
    spuParams.value.category3Id = c3Id
    // 获取所有品牌的数据
    // 获取全部销售属性的数据
    const res: AllTradeMark = await reqAllTrademark()
    allTradeMark.value = res.data;
    const allSaleAttrList: HasSaleAttrResponseData = await reqAllSaleAttr()
    allSaleAttr.value = allSaleAttrList.data;
}
// 照片墙预览图片
const handlePreview = (file: any) => {
    // 修改
    img.value = file.url
    // 默认传入文件对象
    dialogVisible.value = true
}
// 计算出当前spu还未有的销售属性
const unSelectSaleAttr = computed(() => {
    // @ts-ignore
    const unSelectArr = allSaleAttr.value.filter(item => {
        return saleAttr.value.every(item1 => {
            // @ts-ignore
            return item.name !== item1.saleAttrName
        })
    })
    return unSelectArr
})
// 添加销售属性回调
const addSaleAttr = () => {
    // 看门狗
    if (!saleAttrIdAndValueName.value) return
    const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(":")
    // 新的标准格式对象
    const newSaleAttr: SaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [] //新增属性值列表
    }
    // 追加销售属性
    saleAttr.value.push(newSaleAttr)
    // 清空收集的数据
    saleAttrIdAndValueName.value = ""
}
// 输入框和按钮的切换
const toEdit = (row: SaleAttr) => {
    row.flag = true
    row.saleAttrValue = ""
}
// 表单元素失去焦点
const toLook = (row: SaleAttr) => {
    const { baseSaleAttrId, saleAttrValue } = row
    // 整理成服务器需要的属性值
    const newSaleAttrValue: SaleAttrValue = {
        baseSaleAttrId,
        saleAttrValueName: (saleAttrValue as string)
    }
    // 判断是否为空
    if (!saleAttrValue?.trim()) {
        ElMessage.error("请输入属性值")
        return
    }
    // 判断是否重复
    const repeat = row.spuSaleAttrValueList.find(item => {
        return item.saleAttrValueName === saleAttrValue
    })
    if (repeat) {
        ElMessage.error("属性值不能重复")
        return
    }
    // 添加到数组中
    row.spuSaleAttrValueList.push(newSaleAttrValue)
    // 切换为button
    row.flag = false
}
// 保存的回调
const save = async () => {
    // 整理参数
    // 1.整理照片墙数据
    // 照片墙数据并非服务器需要的，将名字和地址更换为imgName和imgUrl
    spuParams.value.spuImageList = imgList.value.map((item: any) => {
        return {
            imgName: item.name,
            imgUrl: (item.response && item.response.data) || item.url,//新增|修改
        }
    })
    // 2.整理销售属性数据
    spuParams.value.spuSaleAttrList = saleAttr.value
    // 发起请求，新增/修改spu
    const res = await addOrUpdateSpu(spuParams.value)
    console.log(res);
    if (res.code == 200) {
        // 返回上一级
        emit("changeScene", {flag: 0, params: '' })
        // 显示修改成功
        ElMessage.success(spuParams.value.id ? "修改成功" : "添加成功")
    }
    else {
        ElMessage.error(spuParams.value.id ? "修改失败" : "添加失败")
    }

}
//对外暴露
defineExpose({
    initHasSpuData,
    initAddSpuData
})
</script>
 
<style lang="scss" scoped></style>